<template>
  <!-- 海外仓下单 -->
  <div class="app-container">
    <el-form
      ref="orderInfo"
      label-width="115px"
      :model="form"
      :rules="rules"
      inline
    >
      <!-- <el-row>
        <el-col :span="24">
          <div class="subtitle">{{ t(`${queryField}customerName`) }}</div>
        </el-col>
      </el-row> -->
      <el-form-item label="客户:" prop="customerCode">
        <el-select
          v-model="form.customerCode"
          style="width: 200px;"
          placeholder="请选择客户"
          clearable
          filterable
        >
          <el-option
            v-for="dict in dicts[DictDirection.客户]"
            :key="dict.customerCode"
            :label="dict.customerName"
            :value="dict.customerCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        id="customCode"
        label="客户单号"
        prop="waybillNo"
        label-width="86px"
      >
        <el-input
          v-model="form.waybillNo"
          clearable
          placeholder="请输入客户单号"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQueryWaybillNo">查询</el-button>
      </el-form-item>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="24">
          <div class="subtitle">收货地址：</div>
        </el-col>
      </el-row>
      <el-form-item label="AmazonCode" prop="code">
        <el-select
          v-model="form.code"
          filterable
          style="width: 200px;"
          placeholder="请输入内容"
        >
          <el-option
            v-for="dict in dicts[DictDirection.AmazonCode]"
            :key="dict.code"
            :label="dict.code"
            :value="dict.code"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="收件人姓名:" prop="consigneeName">
        <el-input
          v-model="form.consigneeName"
          clearable
          style="width: 200px;"
          placeholder="请输入姓名"
        ></el-input>
      </el-form-item>
      <el-form-item label="公司或名字:" prop="consigneeCompany">
        <el-input
          v-model="form.consigneeCompany"
          clearable
          style="width: 200px;"
          placeholder="请输入公司名"
        ></el-input>
      </el-form-item>
      <el-form-item label="电话:" prop="consigneeTel">
        <el-input
          v-model="form.consigneeTel"
          clearable
          style="width: 200px;"
          placeholder="请输入电话"
        ></el-input>
      </el-form-item>
      <el-form-item label="国家:" prop="consigneeCountry">
        <el-select
          v-model="form.consigneeCountry"
          filterable
          clearable
          style="width: 200px;"
          placeholder="请输入内容"
        >
          <el-option
            v-for="dict in dicts[DictDirection.国家]"
            :key="dict.countryCode"
            :label="dict.countryChName"
            :value="dict.countryCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="邮编" prop="consigneePostcode">
        <el-input
          v-model.trim="form.consigneePostcode"
          style="width: 200px;"
          clearable
          placeholder="请输入邮编"
        ></el-input>
      </el-form-item>
      <el-form-item label="城市:" prop="consigneeCity">
        <el-input
          v-model="form.consigneeCity"
          clearable
          style="width: 200px;"
          placeholder="请输入城市"
        ></el-input>
      </el-form-item>
      <el-form-item label="省州:" prop="provinceStateCode">
        <el-input
          v-model="form.provinceStateCode"
          clearable
          style="width: 200px;"
          placeholder="请输入省州"
        ></el-input>
      </el-form-item>
      <el-form-item label="地址一:" prop="consigneeAddress">
        <el-input
          v-model="form.consigneeAddress"
          clearable
          style="width: 200px;"
          placeholder="请输入地址"
        ></el-input>
      </el-form-item>
      <el-form-item label="地址二:" prop="consigneeAddress2">
        <el-input
          v-model="form.consigneeAddress2"
          clearable
          style="width: 200px;"
          placeholder="请输入地址"
        ></el-input>
      </el-form-item>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="24">
          <div class="subtitle">包裹信息：</div>
        </el-col>
        <el-col :span="24">
          <el-scrollbar>
            <div class="mytable">
              <!-- 包裹信息 -->
              <el-row>
                <el-col :span="24">
                  <el-form-item label="包裹种类" prop="goodsType">
                    <el-select v-model="form.goodsType" placeholder="包裹种类">
                      <el-option label="包裹" value="02"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-table
                border
                :data="form.woodInfoList"
                show-summary
                :summary-method="getSummaries"
              >
                <el-table-column
                  label="序号"
                  align="center"
                  width="55"
                  type="index"
                ></el-table-column>
                <el-table-column label="长(cm)" align="center">
                  <template #default="{ row, $index }">
                    <el-form-item :rules="[{ validator: validatePass, message: '长不能为空', trigger: 'blur' }]" label-width="0" :prop="`woodInfoList.${$index}.length`">
                      <el-input-number
                        v-model="row.length"
                        style="width: 100%;"
                        :controls="false"
                        :min="2.54"
                      ></el-input-number>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="宽(cm)" align="center">
                  <template #default="{ row, $index }">
                    <el-form-item :rules="[{ validator: validatePass, message: '宽不能为空', trigger: 'blur' }]" label-width="0" :prop="`woodInfoList.${$index}.width`">
                      <el-input-number
                        v-model="row. width"
                        :controls="false"
                        style="width: 100%;"
                        :min="2.54"
                      ></el-input-number>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="高(cm)" align="center">
                  <template #default="{ row, $index }">
                    <el-form-item :rules="[{ validator: validatePass, message: '高不能为空', trigger: 'blur' }]" label-width="0" :prop="`woodInfoList.${$index}.height`">
                      <el-input-number
                        v-model="row.height"
                        :controls="false"
                        style="width: 100%;"
                        :min="2.54"
                      ></el-input-number>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="重(kg)" align="center">
                  <template #default="{ row, $index }">
                    <el-form-item :rules="[{ validator: validatePass, message: '重量不能为空', trigger: 'blur' }]" label-width="0" :prop="`woodInfoList.${$index}.weight`">
                      <el-input-number
                        v-model="row.weight"
                        :controls="false"
                        style="width: 100%;"
                        :min="0"
                      ></el-input-number>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="件数" align="center">
                  <template #default="{ row, $index }">
                    <el-form-item label-width="0" :rules="[{ validator: validatePass, message: '件数不能为空', trigger: 'blur' }]" :prop="`woodInfoList.${$index}.pieceNumber`">
                      <el-input-number
                        v-model="row.pieceNumber"
                        :controls="false"
                        style="width: 100%;"
                        :min="0"
                      ></el-input-number>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                  <template #default="{ row, $index }">
                    <el-button
                      size="small"
                      icon="el-icon-delete"
                      text
                      @click="handleDeletePackage(row, $index)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-scrollbar>
        </el-col>
        <el-col :span="24">
          <el-button
            :icon="Plus"
            text
            type="primary"
            @click="handleAddPackage"
          >
            添加包裹
          </el-button>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row :gutter="8" type="flex" justify="start">
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="form.remarks"
            style="width: 180px;"
            clearable
            type="textareae"
            autosize
            placeholder="请输入备注"
          >
          </el-input>
        </el-form-item>
        <el-divider></el-divider>
      </el-row>
      <el-row style="display: flow-root;">
        <div class="top-right-btn">
          <el-button type="primary" :loading="btnLoading" @click="submit">下单</el-button>
        </div>
      </el-row>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { ref, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox, ElButton } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n'
import { terminalInfo } from '@/api/expressManager/outSea'
import useDicts, { DictDirection } from '@/store/modules/dicts'

const { t } = useI18n()
const btnLoading = ref(false)
const queryField = 'express.mainBusiness.overseaLocation.overSeaPlaceOrder.queryField.'
const btns = 'express.mainBusiness.overseaLocation.overSeaPlaceOrder.btns.'
const columns = 'express.mainBusiness.overseaLocation.overSeaPlaceOrder.columns.'
const publicKey = 'public.'
const orderInfo = ref(),
  {
    appContext: {
      config: {
        globalProperties: { $validateForm },
      },
    },
  } = getCurrentInstance()
const dicts = useDicts()
dicts.setDicts(DictDirection.客户)
dicts.setDicts(DictDirection.国家)
dicts.setDicts(DictDirection.AmazonCode)
const rules = {
  consigneeName: [
    {
      required: true,
      message: '收件人姓名不能为空',
      trigger: ['blur', 'change'],
    },
  ],
  consigneeTel: [
    {
      required: true,
      message: '电话不能为空',
      trigger: ['blur', 'change'],
    },
  ],

  consigneeAddress: [
    {
      required: true,
      message: '地址不能为空',
      trigger: ['blur', 'change'],
    },
  ],

  consigneeCountry: [
    {
      required: true,
      message: '国家不能为空',
      trigger: ['blur', 'change'],
    },
  ],

  consigneeCity: [
    {
      required: true,
      message: '城市不能为空',
      trigger: ['blur', 'change'],
    },
  ],

  provinceStateCode: [
    {
      required: true,
      message: '州省不能为空',
      trigger: ['blur', 'change'],
    },
  ],

  consigneePostcode: [
    {
      required: true,
      message: '邮编不能为空',
      trigger: ['blur', 'change'],
    },
  ],
  waybillNo: [
    {
      required: true,
      message: '客户单号不能为空',
      trigger: ['blur', 'change'],
    },
  ],
  customerCode: [
    {
      required: true,
      message: '客户不能为空',
      trigger: ['blur', 'change'],
    },
  ],
  goodsType: [
    {
      required: true,
      message: '包裹类型不能为空',
      trigger: 'focus',
    },
  ],
}

const form = ref({
  customerCode: '',

  consigneeName: '',
  consigneeCompany: '',
  consigneeTel: '',
  consigneeAddress: '',
  consigneeAddress2: '',
  remarks: '',
  consigneeCountry: 'US',
  code: '',
  consigneeCity: '',
  provinceStateCode: '',
  consigneePostcode: '',
  shipperName: 'smartPrice',
  waybillNo: '',
  goodsType: '02',
  woodInfoList: [],
})
// eslint-disable-next-line no-redeclare
interface form{
	woodInfoList:string;
	length: string;
   width: string;
	height: string;
	weight: string;
	pieceNumber: string
}

// 查询
const handleQueryWaybillNo = () => {
  
}
// 添加包裹

const handleAddPackage = () => {
  form.value.woodInfoList.push({ length: '', width: '', height: '', weight: '', pieceNumber: '' })
}
const validatePass = (rule, value, callback) => {
  if (value === '' || value == 0 || value == undefined) {
    callback(new Error('请输入包裹信息'))
  } else {
    callback()
  }
}
// 删除包裹
const handleDeletePackage = (row: { [key: string]: any }, index) => {
  ElMessageBox.confirm('此操作将永久删除该包裹信息, 是否继续?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => {
    form.value.woodInfoList.splice(index, 1)
    ElMessage.success('删除成功')
  })
  .catch(() => {
    ElMessage.error('删除失败')
  })
}
// 提交
const { proxy } = getCurrentInstance() as any
const submit = () => {
  $validateForm(orderInfo.value, () => {
    btnLoading.value = true
    terminalInfo(form.value).then(res => {
      if (res.code == 200) {
        ElMessage.success('下单成功')
        btnLoading.value = false
        proxy.$refs.orderInfo.resetFields()
      } else {
        btnLoading.value = false
        ElMessage.error(res.msg)
      }
    }).catch(() => {
      btnLoading.value = false
    })
  })
}
// 合计
const getSummaries = (param) => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const values = data.map((item) => Number(item.pieceNumber))
    sums[5] = values.reduce((prev:string, curr:string) => {
      const value = Number(curr)
      // eslint-disable-next-line no-restricted-globals
      if (!isNaN(value)) {
        return prev + curr
      } 
      return prev
    }, 0)
  })
  return sums
}
</script>
<style lang="less" scoped>
.subtitle {
  font-size: 18px;
  font-weight: 700;
}
.app-container {
  background: #fff;
  margin: 10px;
  border-radius: 10px;
  padding: 10px;
}
.top-right-btn {
  float: right;
  right: 50px;
}
</style>
